/**
 * 
 */
package game.kill.web.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import weixin.popular.bean.message.EventMessage;
import weixin.popular.bean.xmlmessage.XMLMessage;
import weixin.popular.bean.xmlmessage.XMLTextMessage;
import weixin.popular.support.ExpireKey;
import weixin.popular.support.expirekey.DefaultExpireKey;
import weixin.popular.util.SignatureUtil;
import weixin.popular.util.XMLConverUtil;

/**
 * @author leiruiqi
 *
 */

@Controller
public class WecharReceiveController extends BaseController{

	//从官方获取
	private String token = "test";

	//重复通知过滤
	private static ExpireKey expireKey = new DefaultExpireKey();
	
	@RequestMapping("/wecharMessage")
	public void wecharMessage(HttpServletRequest request, HttpServletResponse response) throws IOException{
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        
        //首次请求申请验证,返回echostr
        if(echostr!=null){
            returnJsonString(response, echostr);
            return;
        }

        //验证请求签名
        if(!signature.equals(SignatureUtil.generateEventMessageSignature(token,timestamp,nonce))){
            System.out.println("The request signature is invalid");
            return;
        }
        
      //转换XML
        EventMessage eventMessage = XMLConverUtil.convertToObject(EventMessage.class,request.getInputStream());
        String key = eventMessage.getFromUserName() + "__"
        				   + eventMessage.getToUserName() + "__"
        				   + eventMessage.getMsgId() + "__"
        				   + eventMessage.getCreateTime();
        logger.info("message key:"+key);
        if(expireKey.exists(key)){
        	//重复通知不作处理
        	return;
        }else{
        	expireKey.add(key);
        }

        //创建回复
        XMLMessage xmlTextMessage = new XMLTextMessage(
                eventMessage.getFromUserName(),
                eventMessage.getToUserName(),
                "你说谁");
        
        //回复
        xmlTextMessage.outputStreamWrite(response.getOutputStream());
        return;
        
	}
}
